package models.chat;

import models.ApplicationUser;
import models.chat.messages.Message;
import models.chat.messages.TimePeriod;
import play.db.jpa.Model;

import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author Konovalov_Nik
 */
@Entity
public class Channel extends Model {
    public String name;
    @ElementCollection
    public List<Long> messageIdList = new ArrayList<Long>();
    @ElementCollection
    public List<Long> memberIds = new ArrayList<Long>();

    public Channel(String name) {
        this.name = name;
    }

    public List<ApplicationUser> getMembers() {
        List<ApplicationUser> members = new ArrayList<ApplicationUser>(memberIds.size());
        for (Long memberId : memberIds) {
            members.add((ApplicationUser) ApplicationUser.findById(memberId));
        }
        return members;
    }

    public List<Message> loadMessagesForPeriod(TimePeriod period) {
        long timeBorder = System.currentTimeMillis() - period.getPeriod();
        List<Message> messages = Message.find("byTimestampGreaterThan", timeBorder).fetch();
        for (Message message : new ArrayList<Message>(messages)) {
            if (!messageIdList.contains(message.id)) {
                messages.remove(message);
            }
        }
        Collections.sort(messages, new Comparator<Message>() {
            @Override
            public int compare(Message o1, Message o2) {
                return o1.timestamp.compareTo(o2.timestamp);
            }
        });
        return messages;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Channel)) return false;

        return this.id.equals(((Channel) o).id);

    }

    @Override
    public int hashCode() {
        int result = 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (memberIds != null ? memberIds.hashCode() : 0);
        return result;
    }
}
